package db.nio.handler;

import db.nio.*;
import db.nio.worker.Worker;

import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * 老板工作流水(接收连接处理线程）
 * Created by daibin on 10/27/16.
 */
public class FrontHandler implements Runnable{

    private SocketChannel channel;
    private Worker worker;
    private Processor processor;
    private Encoder encoder;
    private Decoder decoder;
    private Class<? extends Framer> framerClass;


    public FrontHandler(SocketChannel channel, Worker worker, Processor processor, Encoder encoder, Decoder decoder, Class<? extends Framer> framerClass){
        this.channel = channel;
        this.worker = worker;
        this.processor = processor;
        this.encoder = encoder;
        this.decoder = decoder;
        this.framerClass = framerClass;
    }

    /**
     *
     */
    @Override
    public void run() {
        try {

            //绑定通道
            worker.waite = true;
            worker.selector.wakeup();
            SelectionKey selectionKey = channel.register(worker.selector, SelectionKey.OP_READ);
            Framer framer = framerClass.newInstance();
            framer.setSelectionKey(selectionKey);

            ChannelContext context = new ChannelContext(framer, encoder, decoder, processor);
            selectionKey.attach(context);

            worker.waite = false;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
